package com.proton.carepatchtemp.fragment;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.proton.carepatchtemp.R;
import com.proton.carepatchtemp.activity.PrePDFActivity;
import com.proton.carepatchtemp.activity.ReportPngCreateActivity;
import com.proton.carepatchtemp.application.VCare;
import com.proton.carepatchtemp.constant.Extras;
import com.proton.carepatchtemp.constant.Settings;
import com.proton.carepatchtemp.database.daomanager.ProfileManager;
import com.proton.carepatchtemp.database.table.Profile;
import com.proton.carepatchtemp.database.table.Report;
import com.proton.carepatchtemp.utils.FileUtils;
import com.proton.carepatchtemp.utils.FormatUtils;
import com.proton.carepatchtemp.utils.Pdf.PdfUntil;
import com.proton.carepatchtemp.utils.SpUtils;
import com.proton.carepatchtemp.utils.ThreadUtils;
import com.proton.carepatchtemp.utils.net.oss.OSSUtils;
import com.sdsmdg.tastytoast.TastyToast;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXFileObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;

public class ShareReportFragment extends DialogFragment {
    private final String[][] MIME_MapTable = {
//{后缀名，MIME类型}
            {".3gp", "video/3gpp"},
            {".apk", "application/vnd.android.package-archive"},
            {".asf", "video/x-ms-asf"},
            {".avi", "video/x-msvideo"},
            {".bin", "application/octet-stream"},
            {".bmp", "image/bmp"},
            {".c", "text/plain"},
            {".class", "application/octet-stream"},
            {".conf", "text/plain"},
            {".cpp", "text/plain"},
            {".doc", "application/msword"},
            {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
            {".xls", "application/vnd.ms-excel"},
            {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
            {".exe", "application/octet-stream"},
            {".gif", "image/gif"},
            {".gtar", "application/x-gtar"},
            {".gz", "application/x-gzip"},
            {".h", "text/plain"},
            {".htm", "text/html"},
            {".html", "text/html"},
            {".jar", "application/java-archive"},
            {".java", "text/plain"},
            {".jpeg", "image/jpeg"},
            {".jpg", "image/jpeg"},
            {".js", "application/x-JavaScript"},
            {".log", "text/plain"},
            {".m3u", "audio/x-mpegurl"},
            {".m4a", "audio/mp4a-latm"},
            {".m4b", "audio/mp4a-latm"},
            {".m4p", "audio/mp4a-latm"},
            {".m4u", "video/vnd.mpegurl"},
            {".m4v", "video/x-m4v"},
            {".mov", "video/quicktime"},
            {".mp2", "audio/x-mpeg"},
            {".mp3", "audio/x-mpeg"},
            {".mp4", "video/mp4"},
            {".mpc", "application/vnd.mpohun.certificate"},
            {".mpe", "video/mpeg"},
            {".mpeg", "video/mpeg"},
            {".mpg", "video/mpeg"},
            {".mpg4", "video/mp4"},
            {".mpga", "audio/mpeg"},
            {".msg", "application/vnd.ms-outlook"},
            {".ogg", "audio/ogg"},
            {".pdf", "application/pdf"},
            {".png", "image/png"},
            {".pps", "application/vnd.ms-powerpoint"},
            {".ppt", "application/vnd.ms-powerpoint"},
            {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
            {".prop", "text/plain"},
            {".rc", "text/plain"},
            {".rmvb", "audio/x-pn-realaudio"},
            {".rtf", "application/rtf"},
            {".sh", "text/plain"},
            {".tar", "application/x-tar"},
            {".tgz", "application/x-compressed"},
            {".txt", "text/plain"},
            {".wav", "audio/x-wav"},
            {".wma", "audio/x-ms-wma"},
            {".wmv", "audio/x-ms-wmv"},
            {".wps", "application/vnd.ms-works"},
            {".xml", "text/plain"},
            {".z", "application/x-compress"},
            {".zip", "application/x-zip-compressed"},
            {"", "*/*"}
    };
    private IWXAPI api;
    private Report mReport;
    private Profile mProfile;
    private String strPath;
    private File f;
    private LinearLayout mLl_wechat;
    private LinearLayout mLl_wechat_circle;
    private LinearLayout mLl_wechat_mail;
    private LinearLayout mLl_wechat_prelook;
    private TextView mTv_cancel_share;
    private ProgressDialog mDialog;

    public ShareReportFragment() {
    }

    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }
        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private void bindViews(View rootView) {
        mLl_wechat = rootView.findViewById(R.id.ll_wechat);
        mLl_wechat_circle = rootView.findViewById(R.id.ll_wechat_circle);
        mLl_wechat_mail = rootView.findViewById(R.id.ll_wechat_mail);
        mLl_wechat_prelook = rootView.findViewById(R.id.ll_wechat_prelook);
        mTv_cancel_share = rootView.findViewById(R.id.tv_cancel_share);

        if (VCare.isInternal) {
            mLl_wechat_circle.setVisibility(View.GONE);
            mLl_wechat.setVisibility(View.GONE);
        }
    }

    public void setReport(Report report) {
        this.mReport = report;
    }

    //  使得菜单宽度能够适应屏幕
    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (null != dialog) {
            dialog.getWindow().setLayout(-1, -2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //  菜单位于底部设置
        Window window = getDialog().getWindow();
        WindowManager.LayoutParams wlp = window.getAttributes();
        wlp.gravity = Gravity.BOTTOM;
        window.setAttributes(wlp);

        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);

        api = WXAPIFactory.createWXAPI(getActivity(), Settings.WX_APP_ID, true);
        api.registerApp(Settings.WX_APP_ID);
        strPath = FileUtils.getDirectoryP("pdf") + File.separator + String.valueOf(mReport.getId()) + ".pdf";
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_share_report, container, false);
        bindViews(rootView);

        initClick();
        if (SpUtils.getBoolean(Extras.APP_EDITION, false)) {
            mLl_wechat.setVisibility(View.GONE);
            mLl_wechat_circle.setVisibility(View.GONE);
        }
        mDialog = new ProgressDialog(getActivity());
        return rootView;
    }

    public void initClick() {

        mTv_cancel_share.setOnClickListener(v -> {
            ShareReportFragment.this.dismiss();
        });

        mLl_wechat.setOnClickListener(v -> {
            f = new File(strPath);
            if (!f.exists()) {
                createPDF(0);
            } else {
                shareWeChat();
            }
        });

        mLl_wechat_circle.setOnClickListener(v -> {
            f = new File(strPath);
            if (!f.exists()) {
                createPDF(1);
            } else {
                shareWechatCircle();
            }
        });

        mLl_wechat_mail.setOnClickListener(v -> {
            f = new File(strPath);
            if (!f.exists()) {
                createPDF(2);
            } else {
                shareMail();
            }
        });

        mLl_wechat_prelook.setOnClickListener(v -> {
            if (!FileUtils.isFileExist(FileUtils.pdf, mReport.getId() + ".pdf")) {
                createPDF(3);
            } else {
                Intent prePdfIntent = new Intent(getActivity(), PrePDFActivity.class);
                prePdfIntent.putExtra("reportId", mReport.getId());
                prePdfIntent.putExtra("timePeriod", mReport.getEndtime() - mReport.getStarttime());
                startActivity(prePdfIntent);
            }
        });
    }

    private void createPDF(int i) {
        mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置进度条的形式为圆形转动的进度条
        mDialog.setCancelable(true);// 设置是否可以通过点击Back键取消
        mDialog.setCanceledOnTouchOutside(false);// 设置在点击Dialog外是否取消Dialog进度条
        mDialog.setIcon(R.mipmap.ic_launcher);//
        // 设置提示的title的图标，默认是没有的，如果没有设置title的话只设置Icon是不会显示图标的
        mDialog.setTitle(getString(R.string.pdf_creating));
        mDialog.show();
        if (!FileUtils.isFileExist(FileUtils.report, mReport.getId() + ".png")) {
            Intent createPng = new Intent(getActivity(), ReportPngCreateActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable(Extras.REPORT, mReport);
            createPng.putExtras(bundle);
            startActivityForResult(createPng, i);
            return;
        }
        if (FileUtils.isFileExist(FileUtils.report, mReport.getId() + ".png")) {
            new AsyncTask<Void, Void, JSONObject>() {
                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    mDialog.show();
                }

                @Override
                protected JSONObject doInBackground(Void... params) {
                    PdfUntil pdfUntil = new PdfUntil();
                    String msg = VCare.getACacheInstance().getAsString(Extras.ACHCHE_PROFILE);
                    mProfile = ProfileManager.getProfile(mReport.getProfileid());
                    String sex = 1 == mProfile.getGender() ? getString(R.string.female) : getString(R.string.male);
                    String fever;
                    if (Float.parseFloat(mReport.getData().getTemp_max()) > 37.5) {
                        fever = getString(R.string.yes);
                    } else {
                        fever = getString(R.string.no);
                    }
                    String testTime = FormatUtils.formatTime(mReport.getEndtime() - mReport.getStarttime());
                    pdfUntil.createPdf(getActivity(), mProfile.getRealname(), sex, mProfile.getAge(), String.valueOf(mReport.getData().getTemp_max()), fever, testTime, "℃", String.valueOf(mReport.getId()));
                    return null;
                }

                @Override
                protected void onPostExecute(JSONObject aVoid) {
                    super.onPostExecute(aVoid);
                    mDialog.dismiss();
                    switch (i) {
                        case 0:
                            shareWeChat();
                            break;
                        case 1:
                            shareWechatCircle();
                            break;
                        case 2:
                            shareMail();
                            break;
                        case 3:
                            prePdf();
                            break;
                        default:
                            break;
                    }
                    TastyToast.makeText(VCare.get(), getString(R.string.pdf_create_success), TastyToast.LENGTH_SHORT, TastyToast.SUCCESS);
                }
            }.execute();
        }
    }

    private void prePdf() {
        Intent prePdfIntent = new Intent(getActivity(), PrePDFActivity.class);
        prePdfIntent.putExtra("reportId", mReport.getId());
        prePdfIntent.putExtra("timePeriod", mReport.getEndtime() - mReport.getStarttime());
        startActivity(prePdfIntent);
    }

    private void shareWeChat() {
        WXFileObject fileobject = new WXFileObject();
        fileobject.setFilePath(strPath);
        WXMediaMessage mWXMediaMessage = new WXMediaMessage();
        mWXMediaMessage.mediaObject = fileobject;
        mWXMediaMessage.title = mReport.getProfilename() + getString(R.string.one_temp_rpt);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("name");
        req.message = mWXMediaMessage;
        req.scene = SendMessageToWX.Req.WXSceneSession;
        if (api.sendReq(req)) {
            LogUtils.e("Sucess");
        }
    }

    private void shareWechatCircle() {
        f = new File(strPath);
        final byte[] b = FileUtils.getByte(f);
        ThreadUtils.runOnOtherThread(() -> {
            String strUrl = OSSUtils.uploadEcgPdf(b, String.valueOf(mReport.getId()), 2);
            if (TextUtils.isEmpty(strUrl)) {
                LogUtils.e("upload fail");
                //EventBus.getDefault().post(new MainEvent(Codes.NET_RPT_ADD_AUTO, Extras.RET_F, "上传失败"));
            } else {
                WXWebpageObject webpage = new WXWebpageObject();
                webpage.webpageUrl = strUrl;
                WXMediaMessage msg = new WXMediaMessage(webpage);
                msg.title = mReport.getProfilename() + getString(R.string.one_temp_rpt);
                msg.description = getString(R.string.from_care_patch_temprpt);
                Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
                msg.thumbData = bmpToByteArray(thumb, true);
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = buildTransaction("webpdf");
                req.message = msg;
                req.scene = SendMessageToWX.Req.WXSceneTimeline;
                if (api.sendReq(req)) {
                    LogUtils.e("Sucess");
                }
            }
        });
    }

    private void shareMail() {
        f = new File(strPath);
        final byte[] b = FileUtils.getByte(f);
        ThreadUtils.runOnOtherThread(() -> {
            LogUtils.e("Lijin Test Mail = " + strPath);
            if (TextUtils.isEmpty(strPath)) {
                LogUtils.e("upload fail");
                TastyToast.makeText(VCare.get(), getString(R.string.get_file_failed), TastyToast.LENGTH_SHORT, TastyToast.ERROR);
                return;
                //EventBus.getDefault().post(new MainEvent(Codes.NET_RPT_ADD_AUTO, Extras.RET_F, "上传失败"));
            } else {
                String type = getMIMEType(f);
                Uri uri = Uri.parse("file://" + strPath);
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.putExtra(Intent.EXTRA_STREAM, uri);
                intent.putExtra(Intent.EXTRA_SUBJECT, "卡帕奇心电卡心电报告"); // 主题
                intent.putExtra(Intent.EXTRA_TEXT, mReport.getProfilename() + "的心电报告"); // 正文
                intent.setType(type);
                intent.setType("image/*");
                intent.setType("message/rfc882");
                startActivity(Intent.createChooser(intent, "请选择邮件类应用"));
            }
        });
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    /**
     * 根据文件后缀名获得对应的MIME类型。
     */
    private String getMIMEType(File file) {

        String type = "*/*";
        String fName = file.getName();
//获取后缀名前的分隔符"."在fName中的位置。
        int dotIndex = fName.lastIndexOf(".");
        if (dotIndex < 0) {
            return type;
        }
/* 获取文件的后缀名*/
        String end = fName.substring(dotIndex, fName.length()).toLowerCase();
        if (end == "") return type;
//在MIME和文件类型的匹配表中找到对应的MIME类型。
        for (int i = 0; i < MIME_MapTable.length; i++) { //MIME_MapTable??在这里你一定有疑问，这个MIME_MapTable是什么？
            if (end.equals(MIME_MapTable[i][0]))
                type = MIME_MapTable[i][1];
        }
        return type;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        createPDF(requestCode);
        super.onActivityResult(requestCode, resultCode, data);
    }
}
